var TOKEN_STR = "fingerplus";

var tool = require("./tool"),
    path = require("path"),
    crypto = require("crypto"),
    shasum = crypto.createHash('md5'),
    token = shasum.update(TOKEN_STR).digest("hex"),
    deployInfo = require("../../deploy-conf.json"),
    composerPath = !deployInfo.composer ? null : deployInfo.composer,
    composerTo = composerPath ? composerPath.to : "",
    backFaildArr = [],
    backSuccessArr = [];

module.exports = function requestBackPrev(opt, fn) {
    var request = require("request"),
        url = opt.urls.shift(),
        username = opt.username,
        moduleName = opt.modulename;

    tool.stopWaitLog();
    tool.startWaitLog();

    if (url) {
        request.post({
            url: url,
            form: {
                token: token,
                username: username,
                modulename: moduleName,
                composerTo: composerTo
            }
        }, function (err, httpResponse, body) {
            var statusCode = httpResponse && httpResponse.toJSON().statusCode;

            try {
                body = body && JSON.parse(body);
            } catch (e) {
                body = {
                    no: -1,
                    msg: "server is something wrong!"
                }
            }

            if (err || statusCode != 200 || body.no != 0) {
                backFaildArr.push({
                    url: url,
                    status: {
                        code: statusCode || -1,
                        err: err || JSON.stringify(body) || "faild"
                    }
                });
            } else {
                backSuccessArr.push({
                    url: url,
                    status: {
                        code: 200,
                        err: "success"
                    }
                });
            }
            requestBackPrev(opt, fn);
        });
    } else {
        if (!backFaildArr.length) {
            console.log("all servers back to prev complete".green);
        } else {
            console.log("\n" + (backFaildArr.length + " servers back faild: ").red);
            for (var i = 0, len = backFaildArr.length; i < len; i++) {
                console.log(backFaildArr[i].url + " " + JSON.stringify(backFaildArr[i].status));
            }
        }

        fn(backSuccessArr, backFaildArr);
        tool.stopWaitLog();
    }
};
